;$(function() {
	var url = 'http://www.google.com.hk/intl/zh-CN/images/logo_cn.png';
	function getSetWidthHeight(url,limit,callback) {
		var $$ = $(new Image()).one('load' , function() {
			var trueWidth = this.width,trueHeight = this.height;
			var computeWidth,computeHeight;
			if(trueWidth > limit || trueHeight > limit) {
				var max = Math.max(trueWidth,trueHeight);
				if(trueWidth == trueHeight) {
					computeWidth = computeHeight = limit;
				} else if(max == trueWidth) {
					computeWidth = limit;
					computeHeight = limit * trueHeight / trueWidth;
				} else {
					computeHeight = limit;
					computeWidth = trueWidth * limit / trueHeight;	
				}
			} else {
				computeWidth = trueWidth;
				computeHeight = trueHeight;
			}
			$(this).remove();
			callback.call(null,{
				url : url,
				trueWidth : trueWidth,
				trueHeight: trueHeight,
				computeWidth : computeWidth,
				computeHeight: computeHeight
			});
		});	
		$$.attr('src' , url);
		$$ = null;
	}
	getSetWidthHeight(url , 186 , setJcrop);
	
	function setJcrop(obj) {
		$("#jcrop").empty().append('<img src="' + obj.url + '" width="' + obj.computeWidth + '" height="' + obj.computeHeight + '"/>');
		$("#jcrop>img").Jcrop({
            onSelect:    showCoords,
            onChange:    showCoords,
            trueSize:    [obj.trueWidth,obj.trueHeight],
            callback:    function() {
            	var holder = $("#jcrop div.jcrop-holder");
            	var width = holder.width();
		        var height = holder.height();
		        var marginLeft = (186 - width) / 2;
		        var marginTop = (186 - height)/ 2;
		        if(marginLeft > 0) {
		        	holder.css({
		        		marginLeft : marginLeft,
		        		marginRight:marginLeft
		        	});
		        }
		        if(marginTop > 0) {
		        	holder.css({
		        		marginTop : marginTop,
		        		marginBottom:marginTop
		        	});
		        }
            }
        });
    }
	var $result = $("#result");
	function showCoords(obj) {
		$result.val(obj.x + ':' + obj.y + ':' + obj.x2 + ':' + obj.y2);
	}
});